# 请安装 OpenAI SDK : pip install openai
# apiKey 获取地址： https://console.bce.baidu.com/iam/#/iam/apikey/list
# 支持的模型列表： https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Fm2vrveyu
# from openai import OpenAI
# from Config import Config
# client = OpenAI(
#     base_url='https://qianfan.baidubce.com/v2',
#     api_key=Config.APIKey,
#     default_headers={
#         "appid": Config.APPid,
#     }
# )

# messages = [
#     {"role": "user", "content": "你好"},
# ]

# response = client.chat.completions.create(
#     model="ernie-lite-8k", 
#     messages=messages, 
#     temperature=0.95, 
#     top_p=0.7,
#     extra_body={ 
#         "penalty_score":1
#     }
# )
# print(response)

from flask import Flask, jsonify, render_template
from flask_cors import CORS
import matplotlib.pyplot as plt
import numpy as np
import io
import base64
import pandas as pd
from openai import OpenAI
from Config import Config

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 设置字体为微软雅黑

app = Flask(__name__)
CORS(app)  # 解决跨域问题

# 全局数据存储
users = {
    "teachers": {
        1: {"id": 1, "name": "王教授", "email": "teacher1@example.com", "password": "teacher123", "role": "teacher"},
        2: {"id": 2, "name": "李讲师", "email": "teacher2@example.com", "password": "teacher456", "role": "teacher"}
    },
    "students": {
        1: {"id": 1, "name": "张三", "email": "student1@example.com", "password": "student123", "role": "student"},
        2: {"id": 2, "name": "李四", "email": "student2@example.com", "password": "student456", "role": "student"},
        3: {"id": 3, "name": "王五", "email": "student3@example.com", "password": "student789", "role": "student"}
    }
}

courses = {
    1: {
        "id": 1,
        "title": "Python全栈开发",
        "description": "从基础语法到Web开发的全链路课程，适合0基础学员",
        "modules": [
            {"id": 1, "title": "Python基础语法", "duration": 45},
            {"id": 2, "title": "Web框架Flask", "duration": 60},
            {"id": 3, "title": "数据库实战", "duration": 50},
            {"id": 4, "title": "项目部署上线", "duration": 40}
        ],
        "difficulty": "中级",
        "enrollment_count": 1520,
        "completion_rate": 72.8,
        "tags": ["Python", "Web开发", "全栈"],
        "rating": 4.8,
        "related_courses": [2],
        "teacher_id": 1
    },
    2: {
        "id": 2,
        "title": "数据分析与可视化",
        "description": "掌握Python数据分析工具链，从数据清洗到可视化全流程",
        "modules": [
            {"id": 1, "title": "NumPy与Pandas", "duration": 70},
            {"id": 2, "title": "数据可视化Matplotlib", "duration": 60},
            {"id": 3, "title": "实战案例分析", "duration": 80}
        ],
        "difficulty": "中级",
        "enrollment_count": 1280,
        "completion_rate": 65.3,
        "tags": ["数据分析", "可视化", "Python"],
        "rating": 4.7,
        "related_courses": [1, 3],
        "teacher_id": 2
    }
}

# 初始化学习数据
learning_data = pd.DataFrame([
    {"user_id": 1, "course_id": 1, "module_id": 1, "time_spent": 50, "completed": True, "last_accessed": "2025-08-01"},
    {"user_id": 1, "course_id": 1, "module_id": 2, "time_spent": 65, "completed": True, "last_accessed": "2025-08-02"},
    {"user_id": 1, "course_id": 1, "module_id": 3, "time_spent": 40, "completed": False, "last_accessed": "2025-08-03"},
    {"user_id": 2, "course_id": 1, "module_id": 1, "time_spent": 45, "completed": True, "last_accessed": "2025-08-01"},
    {"user_id": 3, "course_id": 2, "module_id": 1, "time_spent": 75, "completed": True, "last_accessed": "2025-08-01"}
])

course_reviews = {
    1: [
        {"user_id": 1, "rating": 5, "comment": "课程内容很实用，老师讲解清晰", "date": "2025-08-05"},
        {"user_id": 2, "rating": 4, "comment": "项目部分可以再深入一些", "date": "2025-08-06"}
    ],
    2: [
        {"user_id": 3, "rating": 5, "comment": "可视化部分案例非常丰富", "date": "2025-08-07"}
    ]
}


# 生成课程数据（基于实际学习数据计算）
def generate_course_data():
    data = {}

    # 处理所有课程的模块
    for course_id, course in courses.items():
        for module in course["modules"]:
            module_title = module["title"]
            # 筛选该模块的学习数据
            module_learning = learning_data[
                (learning_data["course_id"] == course_id) &
                (learning_data["module_id"] == module["id"])
                ]

            total_students = len(module_learning["user_id"].unique())
            completed_students = len(module_learning[module_learning["completed"] == True])

            # 确保不除以零
            if total_students > 0:
                completion_rate = round(completed_students / total_students * 100, 1)
            else:
                completion_rate = 0.0

            data[module_title] = {
                "total_students": total_students,
                "completed": completed_students,
                "completion_rate": completion_rate
            }

    return data


# 使用千问AI分析课程数据
def analyze_course_data(course_data):
    client = OpenAI(
        base_url='https://qianfan.baidubce.com/v2',
        api_key=Config.APIKey,
        default_headers={"appid": Config.APPid}
    )

    # 准备分析提示
    prompt = f"请分析以下课程模块的完课率数据，找出表现最好和最差的模块，并提出改进建议：\n\n"
    for module, data in course_data.items():
        prompt += f"{module}: 总学生数={data['total_students']}, 完成人数={data['completed']}, 完课率={data['completion_rate']}%\n"

    messages = [{"role": "user", "content": prompt}]

    try:
        response = client.chat.completions.create(
            model="ernie-lite-8k",
            messages=messages,
            temperature=0.7,
            top_p=0.8,
            extra_body={"penalty_score": 1}
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        return f"分析过程中出错: {str(e)}"


# 生成柱状图
def generate_completion_chart(course_data):
    modules = list(course_data.keys())
    rates = [data['completion_rate'] for data in course_data.values()]

    plt.figure(figsize=(10, 6))
    bars = plt.bar(modules, rates, color=['#4CAF50', '#2196F3', '#FFC107', '#FF5722', '#9C27B0', '#E91E63', '#673AB7'])
    plt.title('课程模块完课率分析', fontsize=14)
    plt.xlabel('课程模块', fontsize=12)
    plt.ylabel('完课率 (%)', fontsize=12)
    plt.ylim(0, 100)
    plt.grid(axis='y', linestyle='--', alpha=0.7)

    # 在柱顶显示百分比
    for bar in bars:
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width() / 2., height,
                 f'{height}%', ha='center', va='bottom', fontsize=10)

    # 转为Base64编码
    img = io.BytesIO()
    plt.savefig(img, format='png', bbox_inches='tight')
    img.seek(0)
    chart_url = base64.b64encode(img.getvalue()).decode()
    plt.close()

    return f"data:image/png;base64,{chart_url}"


# @app.route('/')
# def index():
#     course_data = generate_course_data()
#     chart_url = generate_completion_chart(course_data)
#     analysis = analyze_course_data(course_data)
#     return render_template('index.html', chart_url=chart_url, analysis=analysis, course_data=course_data)

@app.route('/api/completion-rates')
def get_completion_rates():
    course_data = generate_course_data()
    completion_rates = {
        module: round(data["completed"] / data["total_students"] * 100, 1)
        for module, data in course_data.items() if data["total_students"] > 0
    }
    return jsonify({
        "modules": list(completion_rates.keys()),
        "rates": list(completion_rates.values())
    })


@app.route('/api/completion-chart')
def get_completion_chart():
    course_data = generate_course_data()
    chart_url = generate_completion_chart(course_data)
    return jsonify({"chart": chart_url})


@app.route('/api/analysis')
def get_analysis():
    course_data = generate_course_data()
    analysis = analyze_course_data(course_data)
    return jsonify({"analysis": analysis})


@app.route('/refresh', methods=['POST'])
def refresh():
    course_data = generate_course_data()
    chart_url = generate_completion_chart(course_data)
    analysis = analyze_course_data(course_data)
    return jsonify({
        'chart_url': chart_url,
        'analysis': analysis,
        'course_data': course_data
    })


if __name__ == '__main__':
    app.run(debug=True, port=5000)
